/*
 * @Author: taiyunhang
 * @Date: 2018-04-09 17:15:51
 * */

import injector from 'angular-es-utils/injector';


const dataURItoBlob = dataURI => {
	// convert base64/URLEncoded data component to raw binary data held in a string
	var byteString;
	if (dataURI.split(',')[0].indexOf('base64') >= 0) {
		byteString = atob(dataURI.split(',')[1]);
	} else {
		byteString = unescape(dataURI.split(',')[1]);
	}
	// separate out the mime component
	var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
	// write the bytes of the string to a typed array
	var ia = new Uint8Array(byteString.length);
	for (var i = 0; i < byteString.length; i++) {
		ia[i] = byteString.charCodeAt(i);
	}
	return new Blob([ia], {
		type: mimeString
	});
};

const onLoad = (reader, deferred, scope, file) => {
	return function () {
		scope.$apply(function () {
			var img = new Image();
			// 前端压缩图片
			img.onload = function () {
				// resize the image using canvas
				var canvas = document.createElement('canvas');
				var ctx = canvas.getContext('2d');
				var width = img.width;
				var height = img.height;
				var MAX_WIDTH = width > 2500 ? width / 2 : 2500;
				var MAX_HEIGHT = height > 2500 ? height / 2 : 2500;
				if (width > height) {
					if (width > MAX_WIDTH) {
						height *= MAX_WIDTH / width;
						width = MAX_WIDTH;
					}
				} else {
					if (height > MAX_HEIGHT) {
						width *= MAX_HEIGHT / height;
						height = MAX_HEIGHT;
					}
				}
				canvas.width = width;
				canvas.height = height;
				ctx.drawImage(img, 0, 0, width, height);
				var dataURL = canvas.toDataURL('image/jpeg', 1);
				var blob = dataURItoBlob(dataURL);
				if (blob.size > 2000 * 1024) {
					dataURL = canvas.toDataURL('image/jpeg', 0.2);
				} else if (blob.size > 1000 * 1024) {
					dataURL = canvas.toDataURL('image/jpeg', 0.5);
				} else {
					dataURL = canvas.toDataURL('image/jpeg', 0.8);
				}
				blob = dataURItoBlob(dataURL);
				deferred.resolve(blob);
			};
			img.src = URL.createObjectURL(file);
		});
	};
};

const onError = (reader, deferred, scope) => {
	return function () {
		scope.$apply(function () {
			deferred.reject(reader.result);
		});
	};
};

const onProgress = (reader, scope) => {
	return function (event) {
		scope.$broadcast('imgProgress', {
			total: event.total,
			loaded: event.loaded
		});
	};
};

const getReader = (deferred, scope, file) => {
	var reader = new FileReader();
	reader.onload = onLoad(reader, deferred, scope, file);
	reader.onerror = onError(reader, deferred, scope);
	reader.onprogress = onProgress(reader, scope);
	return reader;
};

const readAsDataUrl = (file, scope) => {
	const $q = injector.get('$q');
	let deferred = $q.defer();
	let reader = getReader(deferred, scope, file);
	reader.readAsDataURL(file);
	return deferred.promise;
};

export { readAsDataUrl };
